package com.xxpay.demo.sdk;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xxpay.demo.enums.PayChannelTypeEnum;
import com.xxpay.demo.util.HttpClientUtils;
import com.xxpay.demo.util.IdWorker;
import com.xxpay.demo.util.IpUtil;
import com.xxpay.demo.util.SignUtils;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName PayRequest
 * @Date 2019/5/4 15:21
 * @Version 1.0
 */
@Slf4j
public class PayRequest {

    private final static String PAY_URL = "http://xxx.xxx.cn/api/pay/create_order";// 支付链接

    private final static String JS_API_PAY_URL = "http://xxx.xxx.cn/pay/temporaryOrder";

    private final static String MCH_ID = "";// 平台分配商户号

    private final static String REQ_KEY = "";// 平台分配 支付请求签名key

    public final static String RES_KEY = ""; //平台分配 支付响应签名key

    /**
     * {@link com.xxpay.demo.enums.PayChannelTypeEnum}
     * 支付类型
     */
    private  String CHANNEL_ID = "WX_JSAPI";

    private final static String CURRENCY = "cny";// 币种 人民币

    private final static int AMOUNT = 100; // 支付金额, 单位 分

    private final static String DEVICE = "ios";


    /**
     * 平台 支付成功 会调用 该支付通知 url 返回 "success" 表示 已接收 支付成功通知,异步通知
     */
    private final static String NOTIFY_URL = "http://wx.xxx.cn/pay/notify.htm";

    /**
     * 支付商品
     */
    private final static String SUBJECT = "商品主题";

    private final static String SUBJECT_BODY = "商品描述";

    private final static String PARAM1 = "";// 拓展参数 1

    private final static String PARAM2 = "";// 拓展参数 2




    /**
     * 除 微信公众号支付 (WX_JSAPI )  之外的支付 示例
     */
    public static String payReq(Integer amount, String channelId, HttpServletRequest request) throws SocketException, UnknownHostException {
        String MCH_ORDER_NO = "M".concat(IdWorker.getStringCode());
        String payUrl = PAY_URL;
        Map<String,Object> reqMap = new HashMap<>();
        reqMap.put("mchId", MCH_ID);
        reqMap.put("mchOrderNo", MCH_ORDER_NO);
        reqMap.put("channelId", channelId);
        reqMap.put("amount",amount);
        reqMap.put("currency", CURRENCY);
        reqMap.put("subject", SUBJECT);
        reqMap.put("body", SUBJECT_BODY);
        reqMap.put("param1", PARAM1);
        reqMap.put("param2", PARAM2);
        reqMap.put("notifyUrl", NOTIFY_URL);

        if(channelId.equals(PayChannelTypeEnum.WX_JSAPI.toString())){

            //微信公众号支付
            payUrl = JS_API_PAY_URL;
            //succeedUrl直接带上参数,只做显示用
            JSONObject jsonObject=new JSONObject();
            //注意此处格式 json
            jsonObject.put("succeedUrl","http://wx.xxx.cn/pay/paySucceed?mchOrderNo="+reqMap.get("mchOrderNo").toString()+"&amount="+amount);
            jsonObject.put("failUrl","http://127.0.0.1:8080/fail");
            reqMap.put("extra",jsonObject.toJSONString());
        }else if(channelId.equals(PayChannelTypeEnum.WX_NATIVE.toString())){
            // 微信扫码支付
            /**
             * productId 为对应 商品ID
             */
            reqMap.put("extra", "{\"productId\":\"test_00011\"}");

        }else if(channelId.equals(PayChannelTypeEnum.WX_MWEB.toString())){
            // 微信H5支付
            /**
             * productId参数必填，对应业务系统定义的商品ID,场景信息sceneInfo(必填)参数见微信商户文档
             */
            reqMap.put("extra", "{\"productId\":\"TEST_1001\",\"sceneInfo\":{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"http://wx.xxx.cn\",\"wap_name\": \"充值测试\"}}}");

        }else if(channelId.equals(PayChannelTypeEnum.ALIPAY_PC.toString())){
            // 支付宝PC支付
            reqMap.put("extra", "{\"qr_pay_mode\":\"\",\"qrcode_width\":\"\",\"fxbackurl\":\"http://wx.xxx.cn/pay/fxbackurl\"}");
        }else if(channelId.equals(PayChannelTypeEnum.ALIPAY_WAP.toString())){
            // 支付宝WAP支付
            reqMap.put("extra", "{\"fxbackurl\":\"http://wx.xxx.cn/pay/fxbackurl\"}");
        }
        reqMap.put("device", DEVICE);
        reqMap.put("clientIp",IpUtil.getIpAddr(request));
        String sign = SignUtils.getSign(reqMap, REQ_KEY);
        reqMap.put("sign", sign);
        String reqStr = JSON.toJSONString(reqMap);
        log.info("调用支付接口请求参数==>{}", reqStr);
        String resp = HttpClientUtils.postStringEntity(payUrl, reqStr);
        log.info("调用支付接口返回结果==>{}", resp);
        Map retMap = JSONObject.parseObject(resp,Map.class);
        //验响应签名
        boolean signResp=SignUtils.verifyPaySign(retMap,PayRequest.RES_KEY,"payParams");
        log.info("验证响应签名结果为:signResp=={}",signResp);
        return resp;
    }

    /***
     * 验签
     * @param args
     */
    public static void main(String[] args) {
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("code","0000");
        retMap.put("msg","success");
        retMap.put("codeUrl","weixin://wxpay/bizpayurl?pr=EI4k393344s");
        retMap.put("payOrderId","P002019034505151228000000");
        retMap.put("prepayId","wx0514333523777015ef6fe537a3946775453");
        retMap.put("sign","C3AB0AB2D060D4377C503042FD28687907");
        boolean sign=SignUtils.verifyPaySign(retMap,PayRequest.RES_KEY,"payParams");
        System.out.println(sign);
    }



}
